package com.twotiger.and.activity.project;

import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.account.recharge.RechargePage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.Coupon;
import com.twotiger.and.bean.ExperienceOrder;
import com.twotiger.and.bean.Interest;
import com.twotiger.and.bean.RechargeBank;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.DateUtil;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.ViewUtils;

/**
 * 体验金的投资确认页面
 * @Description: TODO(这里描述这个类的作用) 
 * @Author gao
 * @Date 2015年8月12日 下午2:46:16
 */
public class ExperienceInverstConfirmPage extends BaseActivity {

    private static final int GETCUNBANKSUCCES = 2;
    private static final int GETCUNBANKFAIL = 3;
    private static final int GETINVESTSUCCES = 4;
    private static final int GETINVESTFAIL = 5;
    public static final int COUPONRESULT_CANCELED = 6; //优惠券暂不使用的标记

    private static final int GETASSERTSUCCES = 7;
    private static final int GETASSERTFAIL = 8;

    private static final int COUNTINVERSTSUCCES = 9;
    private static final int COUNTINVERSTFAIL = 10;

    private TextView sub_title_center_tv;
    private ImageView sub_title_left_bt;
    private TextView project_name;
    private TextView year_interest;
    private TextView repay_type;
    private TextView invest_amount;
    private TextView expect_income;
    private Button confirm_pay;
    private TextView count_time;
    private TextView repay_time;
    private TextView can_inverst;
    private TextView real_amount;
    private HashMap<String, String> parm;
    private ExperienceOrder mExperienceOrder;
    private Double couponvalue = 0.00;
    private List<Coupon> canuse_list;
    private Coupon defaultcoupon;
    private double reallyamount = 0.00; //实际支付金额
    private TextView invest_date;
    private UserAsset userAsset;
    private RechargeBank cunbanklist;
    private Button charge_btn;

    @Override
    protected void processLogic() {
        sub_title_left_bt.setVisibility(View.VISIBLE);
        parm = getParm();
        mExperienceOrder = (ExperienceOrder) getIntent().getExtras().getSerializable("ORDER");
        sub_title_center_tv.setText("订单确认");
        project_name.setText(mExperienceOrder.getProjectname());
        year_interest.setText("" + mExperienceOrder.getProject_yield() + "%");
        repay_type.setText("" + mExperienceOrder.getRepaymenttype());
        invest_date.setText("" + mExperienceOrder.getRecyle() + "天");
        invest_amount.setText("" + ArithUtils.coverMoney(mExperienceOrder.getInverstamount() + "")
                              + "元");
        reallyamount = Double.parseDouble(mExperienceOrder.getRepayAmount());
        count_time.setText("起息时间：" + DateUtil.getlongtoDate(mExperienceOrder.getStartyidtime())
                           + "（明天）");
        repay_time.setText("还款时间：" + DateUtil.getlongtoDate(mExperienceOrder.getStartrepytime()));
        real_amount.setText("实付金额：" + ArithUtils.coverMoney(mExperienceOrder.getRepayAmount() + "")
                            + "元");
        getuserassert();//获取用户账户信息
        countinsert(mExperienceOrder.getInverstamount() + ""); //计算预计收益
        getchargebankcards();
    }

    /**
     * 获取用户已经绑定的银行卡
     */
    private void getchargebankcards() {
        parm.clear();
        parm.put("token", getToken());
        parm.put("type", "recharge");
        getDate(parm, Constants.RECHARGEBANKQUERY, handler, GETCUNBANKSUCCES, GETCUNBANKFAIL,
            true, true, false);
    }

    /**
     * 计算预计收益
     * 
     * @param money
     */
    private void countinsert(String money) {
        parm.clear();
        parm.put("token", getToken());
        parm.put("projectId", mExperienceOrder.getProjectid());
        parm.put("amount", ArithUtils.coverMoney(money));
        parm.put("type", Constants.TYPE_NID_HEIDONG);
        parm.put("mode", mExperienceOrder.getMode());
        getDate(parm, Constants.CALINTEREST, handler, COUNTINVERSTSUCCES, COUNTINVERSTFAIL,
            false, true, false);
    }

    @Override
    protected void onRestart() {
        getuserassert();
        super.onRestart();
    }

    /**
     * 获取账户信息
     */
    private void getuserassert() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.ASSETQUERY, handler, GETASSERTSUCCES, GETASSERTFAIL, false, true,
            false);
    }

    @Override
    protected void setListener() {
        confirm_pay.setOnClickListener(this);
        sub_title_left_bt.setOnClickListener(this);
        charge_btn.setOnClickListener(this);
        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case COUNTINVERSTSUCCES:
                    Basebean result_c = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_c.isOk()) {
                        Interest interest = JSON.parseObject(result_c.data, Interest.class);
                        expect_income.setText(ArithUtils.coverMoney(interest.getInterest() + ""));
                    } else {
                        showToast(result_c.codeDesc);
                    }
                    break;
                case COUNTINVERSTFAIL:
                    showToast("连接失败");
                    break;
                case GETASSERTSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        userAsset = JSONObject.parseObject(result.data, UserAsset.class);
                        mExperienceOrder.setCanuse(userAsset.avaliable);
                        can_inverst.setText("可用余额："
                                            + ArithUtils.coverMoney(mExperienceOrder.getCanuse()
                                                                    + "") + "元");
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case GETASSERTFAIL:
                    showToast("连接失败");
                    break;
                case GETCUNBANKSUCCES:
                    Basebean result_1 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_1.isOk()) {
                        cunbanklist = JSON.parseObject(result_1.data, RechargeBank.class);

                    } else {
                        showToast(result_1.codeDesc);
                    }
                    break;
                case GETCUNBANKFAIL:
                case GETINVESTFAIL:
                    showToast("网络超时");
                    break;
                case GETINVESTSUCCES:
                    Basebean result_i = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_i.isOk()) {
                        BroswerUrl url = JSON.parseObject(result_i.data, BroswerUrl.class);
                        Intent intent = new Intent(mContext, WebViewPage.class);
                        intent.putExtra("url", url.getUrl());
                        intent.putExtra("title", "投资");
                        intent.putExtra("SHOWPASSWORD", "showPassword");
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_INVESTENDLESS);
                        //                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                        startNewActivityforresult(intent, R.anim.push_left_in,
                            R.anim.push_left_out, ProjectDetailPage.TENDERREQUEST);
                    } else {
                        showToast(result_i.codeDesc);
                    }
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    protected void findViewById(View view) {
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        sub_title_left_bt = (ImageView) view.findViewById(R.id.sub_title_left_bt);
        project_name = (TextView) view.findViewById(R.id.project_name);
        year_interest = (TextView) view.findViewById(R.id.year_interest);
        repay_type = (TextView) view.findViewById(R.id.repay_type);
        invest_amount = (TextView) view.findViewById(R.id.invest_amount);
        expect_income = (TextView) view.findViewById(R.id.expect_income);
        count_time = (TextView) view.findViewById(R.id.count_time);
        repay_time = (TextView) view.findViewById(R.id.repay_time);
        can_inverst = (TextView) view.findViewById(R.id.can_inverst);
        charge_btn = (Button) view.findViewById(R.id.charge_btn);
        real_amount = (TextView) view.findViewById(R.id.real_amount);
        confirm_pay = (Button) view.findViewById(R.id.confirm_pay);
        invest_date = (TextView) view.findViewById(R.id.invest_date);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    //提交投资订单
    private void inverst_order() {
        parm.clear();
        parm.put("token", getToken());
        parm.put("projectId", mExperienceOrder.getProjectid());
        parm.put("amount", ArithUtils.coverMoney(reallyamount + ""));
        if (defaultcoupon != null) {
            parm.put("caId", defaultcoupon.getCaId());
        }
        parm.put("type", Constants.TYPE_NID_HEIDONG);
        parm.put("mode", mExperienceOrder.getMode());
        getDate(parm, Constants.INVEST, handler, GETINVESTSUCCES, GETINVESTFAIL, true, true,
            false);
    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.experience_order_confirmation_layout, null);
        return view;
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        if (requestcode == ProjectDetailPage.TENDERREQUEST) {
            if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_SUC) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_SUC);
                finish();
            } else if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_FAI) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_FAI);
                finish();
            }
        }

        super.onActivityResult(requestcode, resultcode, intent);
    }

    @Override
    public void onClick(View view) {
        final Intent intent = new Intent();
        switch (view.getId()) {
        case R.id.sub_title_left_bt:
            onBackPress();
            return;
        case R.id.confirm_pay:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (cunbanklist == null) {
                return;
            }
            if (Double.parseDouble(mExperienceOrder.getRepayAmount()) > (mExperienceOrder
                .getCanuse() + couponvalue)) {
                PromptManager.showConfirmAlert2(mContext, 0, "账户余额不足", "我们先来充个值吧",
                    "充个值", "", false, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            intent.setClass(mContext, RechargePage.class);
                            intent.putExtra("SCENE", RechargePage.SCENE_ORDER);
                            mExperienceOrder.setInverstamount(Double.parseDouble(mExperienceOrder
                                .getRepayAmount())); //因为充值界面用的实付金额是取得Inverstamount字段，所以这里把实付金额赋给Inverstamount
                            intent.putExtra("ORDER", mExperienceOrder);
                            intent.putExtra("COUPON", defaultcoupon);
                            intent.putExtra("RECHARGEBANK", cunbanklist);
                            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                                false);
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
                return;
            }
            inverst_order();
            break;
        case R.id.charge_btn:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (cunbanklist != null) {
                intent.setClass(mContext, RechargePage.class);
                intent.putExtra("CHARGE", mExperienceOrder.getCanuse());
                intent.putExtra("RECHARGEBANK", cunbanklist);
                startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
            }
            break;
        default:
            break;
        }
    }
}
